<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,">





  <link rel="alternate" href="/atom.xml" title="xingyys的个人站点" type="application/atom+xml">






<meta name="description" content="引言在学习了一些简单的数据结构之后，我们要开始相对复杂的数据结构的学习。而今天的主角就是树。之前的数据结构都是一对一的线性结构，但树型结构是一种一对多的数据结构。 树的定义和相关概念树的定义树( Tree)是 n(n&amp;gt;=0) 个结点的有限集。 n=0 时称为空树。 在任意一棵非空树中: ( 1 )有且仅有一个特定的称为根 ( Root )的结点: (2) 当 n&amp;gt;1 时，其余结点可分为">
<meta name="keywords" content="数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="数据结构之树">
<meta property="og:url" content="http://blog.xingyys.club/2019/02/13/数据结构之数/index.html">
<meta property="og:site_name" content="xingyys的个人站点">
<meta property="og:description" content="引言在学习了一些简单的数据结构之后，我们要开始相对复杂的数据结构的学习。而今天的主角就是树。之前的数据结构都是一对一的线性结构，但树型结构是一种一对多的数据结构。 树的定义和相关概念树的定义树( Tree)是 n(n&amp;gt;=0) 个结点的有限集。 n=0 时称为空树。 在任意一棵非空树中: ( 1 )有且仅有一个特定的称为根 ( Root )的结点: (2) 当 n&amp;gt;1 时，其余结点可分为">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.xingyys.club/blog/树.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树1.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树顺序存储.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树链式存储.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树前序遍历.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树中序遍历.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树后序遍历.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树层序遍历.png">
<meta property="og:image" content="http://image.xingyys.club/blog/树转二叉树.png">
<meta property="og:image" content="http://image.xingyys.club/blog/森林转二叉树.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树转树.png">
<meta property="og:image" content="http://image.xingyys.club/blog/二叉树转森林.png">
<meta property="og:image" content="http://image.xingyys.club/blog/哈夫曼树1.png">
<meta property="og:image" content="http://image.xingyys.club/blog/构建哈夫曼树.png">
<meta property="og:updated_time" content="2019-02-18T04:14:38.365Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据结构之树">
<meta name="twitter:description" content="引言在学习了一些简单的数据结构之后，我们要开始相对复杂的数据结构的学习。而今天的主角就是树。之前的数据结构都是一对一的线性结构，但树型结构是一种一对多的数据结构。 树的定义和相关概念树的定义树( Tree)是 n(n&amp;gt;=0) 个结点的有限集。 n=0 时称为空树。 在任意一棵非空树中: ( 1 )有且仅有一个特定的称为根 ( Root )的结点: (2) 当 n&amp;gt;1 时，其余结点可分为">
<meta name="twitter:image" content="http://image.xingyys.club/blog/树.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xingyys.club/2019/02/13/数据结构之数/">





  <title>数据结构之树 | xingyys的个人站点</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xingyys的个人站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学习和分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-users"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xingyys.club/2019/02/13/数据结构之数/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xingyys">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xingyys的个人站点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据结构之树</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-02-13T12:17:29+08:00">
                2019-02-13
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/随笔/" itemprop="url" rel="index">
                    <span itemprop="name">随笔</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>在学习了一些简单的数据结构之后，我们要开始相对复杂的数据结构的学习。而今天的主角就是<code>树</code>。之前的数据结构都是一对一的线性结构，但树型结构是一种一对多的数据结构。</p>
<h1 id="树的定义和相关概念"><a href="#树的定义和相关概念" class="headerlink" title="树的定义和相关概念"></a>树的定义和相关概念</h1><h2 id="树的定义"><a href="#树的定义" class="headerlink" title="树的定义"></a>树的定义</h2><p>树( Tree)是 n(n&gt;=0) 个结点的有限集。 n=0 时称为空树。 在任意一棵非空树中: ( 1 )有且仅有一个特定的称为根 ( Root )的结点: (2) 当 n&gt;1 时，其余结点可分为 m (m&gt;0) 个互不相交的有限集 T1 、 T2、……、 Tm，其中每一个集合本身又是一棵树，并且称为根的子树( SubTree ).如下图所示。</p>
<p><img src="http://image.xingyys.club/blog/树.png" alt=""></p>
<h2 id="树的相关概念"><a href="#树的相关概念" class="headerlink" title="树的相关概念"></a>树的相关概念</h2><p>树是一种复杂的数据结构，相对的树的相关概念也多，下面我们来认识下：</p>
<ul>
<li>树根：树的根结点是唯一的，它是树的起始结点。如图A</li>
<li>结点度：结点拥有的子树树称为结点度。度为0的结点称为<code>叶结点</code>或是<code>终端结点</code>如图G、H、I等。度不为0的结点称为<code>分支结点</code>或是<code>内部结点</code>。</li>
<li>孩子结点，双亲结点：结点的子树称为该结点的<code>孩子结点(Child)</code>或<code>子结点</code>，相应地，该结点就是称为孩子的<code>双亲(Parent)</code>。如A是B的双亲结点，B是A的子结点。同时还有<code>弟兄结点</code>、<code>祖先结点</code>、<code>子孙结点</code>。</li>
<li>树的层次：从根起，根为第一层，根的孩子为第二层。</li>
<li>树的高度：树中结点的最大层次称为树的深度 (Depth)或高度。</li>
<li>森林：森林 (Forest) 是 m (m&gt;=0) 棵互不相交的树的集合。</li>
</ul>
<h1 id="二叉树"><a href="#二叉树" class="headerlink" title="二叉树"></a>二叉树</h1><p>在树型结构中，二叉树应用是最广泛的。</p>
<h2 id="二叉树的定义"><a href="#二叉树的定义" class="headerlink" title="二叉树的定义"></a>二叉树的定义</h2><p>二叉树( Binary Tree) 是 n(n&gt;=0) 个结点的有限集合，该集合或者为空集(称为空二叉树)，或者由一个根结点和两棵互不相交的、分别称为根结点的左子树和右子树的二叉树组成 。</p>
<p><img src="http://image.xingyys.club/blog/二叉树1.png" alt=""></p>
<h2 id="二叉树的特点"><a href="#二叉树的特点" class="headerlink" title="二叉树的特点"></a>二叉树的特点</h2><ol>
<li>每个结点最多有两棵子树。</li>
<li>结点的左子树和右子树的顺序不能调换。</li>
<li>即使树中某结点只有一棵子树，也要区分它是左子树还是右子树。</li>
</ol>
<h2 id="二叉树的五种基本形态"><a href="#二叉树的五种基本形态" class="headerlink" title="二叉树的五种基本形态"></a>二叉树的五种基本形态</h2><ol>
<li>空二叉树</li>
<li>只有一个根结点</li>
<li>根结点只有左子树</li>
<li>根结点只有右子树</li>
<li>根结点既有左子树也有右子树</li>
</ol>
<h2 id="特殊二叉树"><a href="#特殊二叉树" class="headerlink" title="特殊二叉树"></a>特殊二叉树</h2><p><strong>斜树：</strong><br>所有的结点都只有左子树的二叉树称为左斜树。所有结点都是只有右子树的二叉树叫做右斜树。这两种都统称为斜树。斜树有一个特点，就是每层只有一个结点，结点的个数等于二叉树的深度(高度)。</p>
<p><strong>满二叉树：</strong><br>在一颗二叉树中，如果所有分支都存在左子树和右子树，并且所有叶子结点都在同一层上，这样的二叉树称为满二叉树。</p>
<p><strong>完全二叉树：</strong><br>对一颗具有n个结点的二叉树按层序编号，如果编号为i(1≤i≤n)结点与同样深度的满二叉树中编号为i的结点在二叉树中位置完全相同，则这棵二叉树称为完全二叉树。</p>
<h2 id="二叉树的性质"><a href="#二叉树的性质" class="headerlink" title="二叉树的性质"></a>二叉树的性质</h2><ol>
<li>性质一：在二叉树的第 i 层上至多有 2^i-1^ 个结点 (i≥1) 。</li>
<li>性质二: 深度为 k 的二叉树至多有 2^k^-1 个结点 (k≥1) 。</li>
<li>性质三：对任何一课二叉树T，如果其终端结点数为n~0~，度为2的结点树为n~2~，则n~0~=n~2~+1。</li>
<li>性质四：具有n个结点的完全二叉树的深度为[log~2~n]+1。</li>
<li>性质五：如果对一棵有n个结点的完全二叉树（其深度为[log~2~n]+1）的结点层序编号（从第1层到第[log~2~n]+1层，每层从左到右），对任一结点i（1≤i≤n）有：<ul>
<li>如果i=1，则结点i是二叉树的跟，无双亲；如果i&gt;1，则其双亲是结点[i/2]。</li>
<li>如果2i&gt;n，则结点i无左孩子（结点i为叶子结点）；否则其左孩子是结点2i。</li>
<li>如果2i+1&gt;n，则结点i无右孩子；否则其右孩子结点为2i+1。</li>
</ul>
</li>
<li>已知前序遍历序列和中序遍历序列，可以唯一确定一棵二叉树。</li>
<li>已知后序遍历序列和中序遍历序列，可以唯一确定一棵二叉树</li>
</ol>
<h2 id="二叉树的存储结构"><a href="#二叉树的存储结构" class="headerlink" title="二叉树的存储结构"></a>二叉树的存储结构</h2><p><strong>顺序存储</strong><br>由于二叉树的特殊性，使得用顺序存储结构也可以实现。</p>
<p><img src="http://image.xingyys.club/blog/二叉树顺序存储.png" alt=""></p>
<p>不存在的点，在线性表中使用^代替。尽管可以使用存储结构，但是它的适用性不强。所以我们在来看它的链式结构。</p>
<p><strong>链式存储</strong><br>二叉树的每个结点最多有两个孩子，所以在程序中表现出有三个域，分别为<code>数据域</code>，<code>左孩子指针域</code>和<code>右孩子指针域</code>。</p>
<p><img src="http://image.xingyys.club/blog/二叉树链式存储.png" alt=""></p>
<h2 id="二叉树实现"><a href="#二叉树实现" class="headerlink" title="二叉树实现"></a>二叉树实现</h2><h3 id="二叉树结点"><a href="#二叉树结点" class="headerlink" title="二叉树结点"></a>二叉树结点</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BinTNode</span>:</span></span><br><span class="line">	<span class="string">"""二叉树结点，包含三个域"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data, left=None, right=None)</span>:</span></span><br><span class="line">        self.data = data</span><br><span class="line">        self.left = left</span><br><span class="line">        self.right = right</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BinTree</span>:</span></span><br><span class="line">	<span class="string">"""二叉树"""</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.root = <span class="keyword">None</span></span><br><span class="line">		</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">append</span><span class="params">(self, data)</span>:</span></span><br><span class="line">        node = BinTNode(data)</span><br><span class="line">        <span class="keyword">if</span> self.root <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">            self.root = node</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            q = [self.root]</span><br><span class="line"></span><br><span class="line">            <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">                pop_node = q.pop(<span class="number">0</span>)</span><br><span class="line">                <span class="keyword">if</span> pop_node.left <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">                    pop_node.left = node</span><br><span class="line">                    <span class="keyword">return</span></span><br><span class="line">                <span class="keyword">elif</span> pop_node.right <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">                    pop_node.right = node</span><br><span class="line">                    <span class="keyword">return</span></span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    q.append(pop_node.left)</span><br><span class="line">                    q.append(pop_node.right)</span><br></pre></td></tr></table></figure>
<h3 id="二叉树的遍历"><a href="#二叉树的遍历" class="headerlink" title="二叉树的遍历"></a>二叉树的遍历</h3><p><code>二叉树的遍历(traversing binary tree)是指从根出发，按照某种次序依次访问二叉树中所有结点，使得每个结点被访问一次且仅被访问一次。</code>二叉树的遍历方法一共有四种：</p>
<p><strong>1.前序遍历</strong><br>规则是若二叉树为空，则空操作返回，否则先访问根结点，然后前序遍历左子树， 再前序遍历右子树。如图遍历顺序为：ABDGHCEIF。</p>
<p><img src="http://image.xingyys.club/blog/二叉树前序遍历.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">preorder</span><span class="params">(self, root)</span>:</span>  <span class="comment"># 前序序遍历</span></span><br><span class="line">    <span class="keyword">if</span> root <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">return</span> []</span><br><span class="line">    result = [root.data]</span><br><span class="line">    left = self.preorder(root.left)</span><br><span class="line">    right = self.preorder(root.right)</span><br><span class="line">    <span class="keyword">return</span> result + left + right</span><br></pre></td></tr></table></figure>
<p><strong>2.中序遍历</strong><br>规则是若树为空，则空操作返回，否则从根结点开始(注意并不是先访问根结点) ，中序遍历根结点的左子树，然后是访问根结点，最后中序遍历右子树 。 如下图所示， 遍历的顺序为为:GDHBAEICF 。</p>
<p><img src="http://image.xingyys.club/blog/二叉树中序遍历.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">inorder</span><span class="params">(self, root)</span>:</span>  <span class="comment"># 中序遍历</span></span><br><span class="line">    <span class="keyword">if</span> root <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">return</span> []</span><br><span class="line">    result = [root.data]</span><br><span class="line">    left = self.inorder(root.left)</span><br><span class="line">    right = self.inorder(root.right)</span><br><span class="line">    <span class="keyword">return</span> left + result + right</span><br></pre></td></tr></table></figure>
<p><strong>3.后序遍历</strong><br>规则是若树为空，则空操作返回，否则从左到右先叶子后结点的方式遍历访问左右子树，最后是访问根结点。 如图下所示，遍历的顺序为: GHDBIEFCA。</p>
<p><img src="http://image.xingyys.club/blog/二叉树后序遍历.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">postorder</span><span class="params">(self, root)</span>:</span>  <span class="comment"># 后序遍历</span></span><br><span class="line">    <span class="keyword">if</span> root <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">return</span> []</span><br><span class="line">    result = [root.data]</span><br><span class="line">    left = self.postorder(root.left)</span><br><span class="line">    right = self.postorder(root.right)</span><br><span class="line">    <span class="keyword">return</span> left + right + result</span><br></pre></td></tr></table></figure>
<p><strong>4.层序遍历</strong><br>规则是若树为空 ， 则空操作返回，否则从树的第一层，也就是根结点开始访问，从上而下逐层遍历，在同一层中 ， 按从左到右的颇用才结点逐个访问。如图下所示，遍历的顺序为:ABCDEFGHL。</p>
<p><img src="http://image.xingyys.club/blog/二叉树层序遍历.png" alt=""></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">traverse</span><span class="params">(self)</span>:</span>  <span class="comment"># 层次遍历</span></span><br><span class="line">    <span class="keyword">if</span> self.root <span class="keyword">is</span> <span class="keyword">None</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">None</span></span><br><span class="line">    q = [self.root]</span><br><span class="line">    res = [self.root.data]</span><br><span class="line">    <span class="keyword">while</span> len(q) == <span class="number">0</span>:</span><br><span class="line">        pop_node = q.pop(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">if</span> pop_node.left <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">            q.append(pop_node.left)</span><br><span class="line">            res.append(pop_node.left.data)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> pop_node.right <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">            q.append(pop_node.right)</span><br><span class="line">            res.append(pop_node.right.data)</span><br><span class="line">    <span class="keyword">return</span> res</span><br></pre></td></tr></table></figure>
<h1 id="树、森林和二叉树的转化"><a href="#树、森林和二叉树的转化" class="headerlink" title="树、森林和二叉树的转化"></a>树、森林和二叉树的转化</h1><h2 id="树转化为二叉树"><a href="#树转化为二叉树" class="headerlink" title="树转化为二叉树"></a>树转化为二叉树</h2><p>将树转换为二叉树的步骤如下：</p>
<ol>
<li>加线。在所有弟兄结点之间加一条连线。 </li>
<li>去线。对树中每个结点，只保留它与第一个结点的连线，删除它与其他孩子结点之间的连线。</li>
<li>层次调整。以树的根结点为轴心，将整棵树顺时针旋转一定角度，使之结构层次分明。注意第一个孩子是二叉树结点的左孩子，弟兄转化过来的孩子是结点的右孩子。</li>
</ol>
<p><img src="http://image.xingyys.club/blog/树转二叉树.png" alt=""></p>
<h2 id="森林转化为二叉树"><a href="#森林转化为二叉树" class="headerlink" title="森林转化为二叉树"></a>森林转化为二叉树</h2><p>森林是由若干棵树组成的，所以完全可以理解为，森林中的每一棵树都是弟兄，可以按照弟兄的处理方法来操作。步骤如下：</p>
<ol>
<li>把每个树转换为二叉树。</li>
<li>第一棵二叉树不动，从第二棵二叉树开始，依次把后一棵二叉树的根节点作为前一棵二叉树的根结点的右孩子，用线连起来。当所有的二叉树连接起来后就得到了由森林转换来的二叉树。</li>
</ol>
<p><img src="http://image.xingyys.club/blog/森林转二叉树.png" alt=""></p>
<h2 id="二叉树转化为树"><a href="#二叉树转化为树" class="headerlink" title="二叉树转化为树"></a>二叉树转化为树</h2><p>二叉树转换为树是树转换为二叉树的逆过程，也就是反过来做而已。步骤如下:</p>
<ol>
<li>加线。若某结点的左孩子结点存在，则将这个左孩子的右孩子结点、右孩子的右孩子结点、右孩子的右孩子的右孩子结点……哈，反正就是左孩子的 n个右孩子结点都作为此结点的孩子。将该结点与这些右孩子结点用线连接起来。</li>
<li>去钱。删除原二叉树中所有结点与其右孩子结点的连线。</li>
<li>层次调整 。使之结构层次分明。</li>
</ol>
<p><img src="http://image.xingyys.club/blog/二叉树转树.png" alt=""></p>
<h2 id="二叉树转化为森林"><a href="#二叉树转化为森林" class="headerlink" title="二叉树转化为森林"></a>二叉树转化为森林</h2><p>判断一棵二叉树能够转换成一棵树还是森林，标准很简单 ， 那就是只要看这棵二叉树的根结点有没有右孩子，有就是森林，没有就是一棵树。那么如果是转换成森林，步骤如下 :</p>
<ol>
<li>从根结点开始 ， 若右孩子存在，则把与右孩子结点的连线删除 ，再查看分离后的二叉树，若右孩子存在，则连续删除……，直到所有右孩子连线都删除为止，得到分离的二叉树。</li>
<li>再将每棵分离后的二叉树转换为树即可。</li>
</ol>
<p><img src="http://image.xingyys.club/blog/二叉树转森林.png" alt=""></p>
<h1 id="哈夫曼树"><a href="#哈夫曼树" class="headerlink" title="哈夫曼树"></a>哈夫曼树</h1><p>接下来我们来了解一种特殊的二叉树，名叫哈夫曼树，也叫最优二叉树。</p>
<h2 id="什么是哈夫曼树"><a href="#什么是哈夫曼树" class="headerlink" title="什么是哈夫曼树"></a>什么是哈夫曼树</h2><p>在认识哈夫曼树之前，我们先来了解一下相关的概念。</p>
<p><img src="http://image.xingyys.club/blog/哈夫曼树1.png" alt=""></p>
<p>首先<code>从树中一个结点到另一个结点之间的分支构成两个结点之间的路径，路径上的分支数目称做路径长度</code>。图中二叉树 a 中， 根结点到结点 D 的路径长度就为 4 ，二叉树 b 中根结点到结点 D 的路径长度为 2 。 <code>树的路径长度就是从树根到每一结点的路径长度之和</code>。 二 叉树 a 的树路径长度就为1+1+2+2+3+3+4叫=20 。二叉树 b 的树路才告氏度就为 1+2+3+3+2+1+2+2=16 。<br>如果考虑到带权的结点，结点的带权的路径长度为从该结点到树根之间的路径长度与结点上权的乘积。树的带权路径长度为树中所有叶子结点的带权路径长度之和 。<br>假设有 n 个权值{W~1,~W~2~.…，W~n~} ，构造一棵有 n 个叶子结点的二叉树，每个叶子结点带权 W~k~，每个叶子的路径长度为 l~k~ ，通常记作WPL，则其中<code>带权路径长度 WPL 最小的二叉树称做赫夫曼树</code>。</p>
<ul>
<li>二叉树a的WPL=5x1+15x2+40X3+30x4+10x4=315</li>
<li>二叉树 b 的 WPL=5x3+15x3+40x2+30x2+10x2=220</li>
</ul>
<h2 id="构造哈夫曼树"><a href="#构造哈夫曼树" class="headerlink" title="构造哈夫曼树"></a>构造哈夫曼树</h2><p>一般构建哈夫曼树有以下步骤：</p>
<ol>
<li>将所有左，右子树都为空的作为根节点。</li>
<li>在森林中选出两棵根节点的权值最小的树作为一棵新树的左，右子树，且置新树的附加根节点的权值为其左，右子树上根节点的权值之和。注意，左子树的权值应小于右子树的权值。</li>
<li>从森林中删除这两棵树，同时把新树加入到森林中。</li>
<li>重复2，3步骤，直到森林中只有一棵树为止，此树便是哈夫曼树。</li>
</ol>
<p><img src="http://image.xingyys.club/blog/构建哈夫曼树.png" alt=""></p>
<h2 id="哈夫曼编码"><a href="#哈夫曼编码" class="headerlink" title="哈夫曼编码"></a>哈夫曼编码</h2><p>哈夫曼树被发明出来的最初目的是解决远距离通讯的数据传输的最优化问题。在远程传输中数据都是以二进制格式传输的。因为编码中非 0 即 1 ，长短不等的话其实是很容易混淆的，所以<code>若要设计长短不等的编码，则必须是任一字符的编码都不是另一个字符的编码的前缀，这种编码称做前缀编码</code>。</p>
<p>通过哈夫曼树来构造的编码称为哈夫曼编码：</p>
<ol>
<li>利用字符集中每个字符的使用频率作为权值构造一个哈夫曼树； </li>
<li>从根结点开始，为到每个叶子结点路径上的左分支赋予0，右分支赋予1，并从根到叶子方向形成该叶子结点的编码。</li>
</ol>
<h2 id="哈夫曼编码的实现"><a href="#哈夫曼编码的实现" class="headerlink" title="哈夫曼编码的实现"></a>哈夫曼编码的实现</h2><p>先来梳理下过程：</p>
<ol>
<li>统计给定字符串的字符频率。</li>
<li>创建树结点。</li>
<li>创建结点队列。</li>
<li>创建哈夫曼树。</li>
<li>编码表。</li>
</ol>
<p><strong>1.统计字符串字符频率</strong><br>假设给定一个字符创：<br><code>s = &quot;AAGGDCCCDDDGFBBBFFGGDDDDGGGEFFDDCCCCDDFGAAA&quot;</code><br>我们先来统计该字符串字符出现频率。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 各个字符在字符串中出现的次数，即计算优先度</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">freChar</span><span class="params">(s)</span>:</span></span><br><span class="line">    d = &#123;&#125;</span><br><span class="line">    <span class="keyword">for</span> c <span class="keyword">in</span> s:</span><br><span class="line">        <span class="keyword">if</span> c <span class="keyword">not</span> <span class="keyword">in</span> d:</span><br><span class="line">            d[c] = <span class="number">1</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            d[c] += <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> sorted(d.items(), key=<span class="keyword">lambda</span> x: x[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出结果</span></span><br><span class="line"><span class="comment"># [('E', 1), ('B', 3), ('A', 5), ('F', 6), ('C', 7), ('G', 9), ('D', 12)]</span></span><br></pre></td></tr></table></figure></p>
<p><strong>2. 创建树结点</strong><br>统计完字符串中各字符的频率后，我们就来根据输出值来创建树结点。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 树节点类构建</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TreeNode</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, data)</span>:</span></span><br><span class="line">        self.val = data[<span class="number">0</span>]      <span class="comment"># 结点数据</span></span><br><span class="line">        self.priority = data[<span class="number">1</span>] <span class="comment"># 结点的权</span></span><br><span class="line">        self.leftChild = <span class="keyword">None</span>   <span class="comment"># 左子树指针</span></span><br><span class="line">        self.rightChild = <span class="keyword">None</span>  <span class="comment"># 右子树指针</span></span><br><span class="line">        self.code = <span class="string">""</span>          <span class="comment"># 结点值的编码</span></span><br></pre></td></tr></table></figure></p>
<p><strong>3. 创建结点队列。</strong><br>创建一个结点队列，这个队列中的元素按照结点权值的大小排列。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建树节点队列函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">creatnodeQ</span><span class="params">(codes)</span>:</span></span><br><span class="line">    q = []</span><br><span class="line">    <span class="keyword">for</span> code <span class="keyword">in</span> codes:</span><br><span class="line">        q.append(TreeNode(code))</span><br><span class="line">    <span class="keyword">return</span> q</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 为队列添加节点元素，并保证优先度从大到小排列</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">addQ</span><span class="params">(queue, nodeNew)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> len(queue) == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">return</span> [nodeNew]</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(len(queue)):</span><br><span class="line">        <span class="keyword">if</span> queue[i].priority &gt;= nodeNew.priority:</span><br><span class="line">            <span class="keyword">return</span> queue[:i] + [nodeNew] + queue[i:]</span><br><span class="line">    <span class="keyword">return</span> queue + [nodeNew]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 节点队列类定义</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">nodeQeuen</span><span class="params">(object)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, code)</span>:</span></span><br><span class="line">        self.que = creatnodeQ(code)</span><br><span class="line">        self.size = len(self.que)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">addNode</span><span class="params">(self, node)</span>:</span></span><br><span class="line">        self.que = addQ(self.que, node)</span><br><span class="line">        self.size += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">popNode</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.size -= <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> self.que.pop(<span class="number">0</span>)</span><br></pre></td></tr></table></figure></p>
<p><strong>4. 创建哈夫曼树。</strong><br>根据已经排序好的队列，我们就可以利用哈夫曼树的构造规则开始构造了<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建哈夫曼树</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">creatHuffmanTree</span><span class="params">(nodeQ)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> nodeQ.size != <span class="number">1</span>:</span><br><span class="line">        node1 = nodeQ.popNode()</span><br><span class="line">        node2 = nodeQ.popNode()</span><br><span class="line">        r = TreeNode([<span class="keyword">None</span>, node1.priority + node2.priority])</span><br><span class="line">        r.leftChild = node1</span><br><span class="line">        r.rightChild = node2</span><br><span class="line">        nodeQ.addNode(r)</span><br><span class="line">    <span class="keyword">return</span> nodeQ.popNode()</span><br></pre></td></tr></table></figure></p>
<p><strong>5. 编码表。</strong><br>哈夫曼编码用于数据的传输，所以会涉及到数据的编码和解码，所以创建两张表，分别用来编码和解码。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">codeDic1 = &#123;&#125;</span><br><span class="line">codeDic2 = &#123;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 由哈夫曼树得到哈夫曼编码表</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">HuffmanCodeDic</span><span class="params">(head, x)</span>:</span></span><br><span class="line">    <span class="keyword">global</span> codeDic, codeList</span><br><span class="line">    <span class="keyword">if</span> head:</span><br><span class="line">        HuffmanCodeDic(head.leftChild, x + <span class="string">'0'</span>)</span><br><span class="line">        head.code += x</span><br><span class="line">        <span class="keyword">if</span> head.val:</span><br><span class="line">            codeDic2[head.code] = head.val</span><br><span class="line">            codeDic1[head.val] = head.code</span><br><span class="line">        HuffmanCodeDic(head.rightChild, x + <span class="string">'1'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 字符串编码</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">TransEncode</span><span class="params">(string)</span>:</span></span><br><span class="line">    <span class="keyword">global</span> codeDic1</span><br><span class="line">    transcode = <span class="string">""</span></span><br><span class="line">    <span class="keyword">for</span> c <span class="keyword">in</span> string:</span><br><span class="line">        transcode += codeDic1[c]</span><br><span class="line">    <span class="keyword">return</span> transcode</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 字符串解码</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">TransDecode</span><span class="params">(StringCode)</span>:</span></span><br><span class="line">    <span class="keyword">global</span> codeDic2</span><br><span class="line">    code = <span class="string">""</span></span><br><span class="line">    ans = <span class="string">""</span></span><br><span class="line">    <span class="keyword">for</span> ch <span class="keyword">in</span> StringCode:</span><br><span class="line">        code += ch</span><br><span class="line">        <span class="keyword">if</span> code <span class="keyword">in</span> codeDic2:</span><br><span class="line">            ans += codeDic2[code]</span><br><span class="line">            code = <span class="string">""</span></span><br><span class="line">    <span class="keyword">return</span> ans</span><br></pre></td></tr></table></figure></p>
<p>所有的步骤都准备好了，开始执行：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 举例</span></span><br><span class="line">s = <span class="string">"AAGGDCCCDDDGFBBBFFGGDDDDGGGEFFDDCCCCDDFGAAA"</span></span><br><span class="line">t = nodeQeuen(freChar(s))</span><br><span class="line">tree = creatHuffmanTree(t)</span><br><span class="line">HuffmanCodeDic(tree, <span class="string">''</span>)</span><br><span class="line">print(codeDic1, codeDic2)</span><br><span class="line">a = TransEncode(s)</span><br><span class="line">print(a)</span><br><span class="line">aa = TransDecode(a)</span><br><span class="line">print(aa)</span><br><span class="line">print(s == aa)</span><br><span class="line"></span><br><span class="line"><span class="comment">#======== 下面是输出 =========</span></span><br><span class="line"><span class="comment"># &#123;'E': '0000', 'B': '0001', 'A': '001', 'G': '01', 'D': '10', 'F': '110', 'C': '111'&#125; &#123;'0000': 'E', # '0001': 'B', '001': 'A', '01': 'G', '10': 'D', '110': 'F', '111': 'C'&#125;</span></span><br><span class="line"><span class="comment"># 0010010101101111111111010100111000010001000111011001011010101001010100001101101010111111111111101011001001001001</span></span><br><span class="line"><span class="comment"># AAGGDCCCDDDGFBBBFFGGDDDDGGGEFFDDCCCCDDFGAAA</span></span><br><span class="line"><span class="comment"># True</span></span><br></pre></td></tr></table></figure></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>今天的内容有点多。我们主要来学习树的内容。首先是了解了什么是树，然后在这个的基础上，学习了树中一种最常用的二叉树。之后又学习了森林，树和二叉树之间的转化。而二叉树在信息传输上也有重要的用途，就是哈夫曼编码。</p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li>数据结构和算法Python实现</li>
<li>大话数据结构</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="xingyys 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数据结构/" rel="tag"># 数据结构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/11/数据结构之字符串/" rel="next" title="数据结构之字符串">
                <i class="fa fa-chevron-left"></i> 数据结构之字符串
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/02/15/golang打包和解包/" rel="prev" title="golang打包和解包">
                golang打包和解包 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjIyNC8xODc3MQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="xingyys">
            
              <p class="site-author-name" itemprop="name">xingyys</p>
              <p class="site-description motion-element" itemprop="description">你的话是我脚前的灯，是我路上的光。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xingyys" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#树的定义和相关概念"><span class="nav-number">2.</span> <span class="nav-text">树的定义和相关概念</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#树的定义"><span class="nav-number">2.1.</span> <span class="nav-text">树的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#树的相关概念"><span class="nav-number">2.2.</span> <span class="nav-text">树的相关概念</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二叉树"><span class="nav-number">3.</span> <span class="nav-text">二叉树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的定义"><span class="nav-number">3.1.</span> <span class="nav-text">二叉树的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的特点"><span class="nav-number">3.2.</span> <span class="nav-text">二叉树的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的五种基本形态"><span class="nav-number">3.3.</span> <span class="nav-text">二叉树的五种基本形态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#特殊二叉树"><span class="nav-number">3.4.</span> <span class="nav-text">特殊二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的性质"><span class="nav-number">3.5.</span> <span class="nav-text">二叉树的性质</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的存储结构"><span class="nav-number">3.6.</span> <span class="nav-text">二叉树的存储结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树实现"><span class="nav-number">3.7.</span> <span class="nav-text">二叉树实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#二叉树结点"><span class="nav-number">3.7.1.</span> <span class="nav-text">二叉树结点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二叉树的遍历"><span class="nav-number">3.7.2.</span> <span class="nav-text">二叉树的遍历</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#树、森林和二叉树的转化"><span class="nav-number">4.</span> <span class="nav-text">树、森林和二叉树的转化</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#树转化为二叉树"><span class="nav-number">4.1.</span> <span class="nav-text">树转化为二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#森林转化为二叉树"><span class="nav-number">4.2.</span> <span class="nav-text">森林转化为二叉树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树转化为树"><span class="nav-number">4.3.</span> <span class="nav-text">二叉树转化为树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树转化为森林"><span class="nav-number">4.4.</span> <span class="nav-text">二叉树转化为森林</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#哈夫曼树"><span class="nav-number">5.</span> <span class="nav-text">哈夫曼树</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是哈夫曼树"><span class="nav-number">5.1.</span> <span class="nav-text">什么是哈夫曼树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#构造哈夫曼树"><span class="nav-number">5.2.</span> <span class="nav-text">构造哈夫曼树</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#哈夫曼编码"><span class="nav-number">5.3.</span> <span class="nav-text">哈夫曼编码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#哈夫曼编码的实现"><span class="nav-number">5.4.</span> <span class="nav-text">哈夫曼编码的实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xingyys</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
